package com.rednote.controller;

import com.rednote.common.JwtUtil;
import com.rednote.common.OssUtil;
import com.rednote.common.Result;

import com.rednote.common.UserContextHolder;
import com.rednote.entity.dto.UserDTO;
import com.rednote.entity.vo.UserProfileVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.rednote.entity.Users;
import com.rednote.service.UsersService;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * 用户基本信息表(Users)控制层
 *
 * @author yao suxuan
 * @since 2025-05-24 17:50:51
 */
@RestController
@RequestMapping("/user")
public class UsersController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Resource
    private UsersService usersService;
    @Resource
    private JwtUtil jwtUtil = new JwtUtil();
    @Resource
    private OssUtil ossUtil;

    /**
     * 用户注册接口
     * @param user 用户信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody Users user) {
        if (user.getAccount() == null || user.getPassword() == null) {
            return Result.fail("账号和密码不能为空");
        }
        
        // 判断account是邮箱还是手机号
        String account = user.getAccount();
        String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
        String phoneRegex = "^1[3-9]\\d{9}$";
        
        if (account.matches(emailRegex)) {
            user.setEmail(account);
        } else if (account.matches(phoneRegex)) {
            user.setPhone(account);
        } else {
            return Result.fail("账号格式不正确，请输入正确的邮箱或手机号");
        }

        // 如果用户名为空，设置一个随机用户名
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            String randomUsername = "用户" + UUID.randomUUID().toString().substring(0, 8);
            user.setUsername(randomUsername);
        }
        
        // 密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        
        // 设置默认值
        user.setAvatar("avatars/2b212a71-8b35-4423-a5f3-1ef23feda9e4.png");
        user.setGender(0);
        user.setBio("这个人很懒，什么都没有留下");
        user.setStatus(1);
        user.setCreatedAt(new Date());
        
        // 调用service进行注册
        Users registeredUser = usersService.register(user);
        if (registeredUser != null) {
            // 生成JWT token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", registeredUser.getUserId());
            claims.put("account", registeredUser.getAccount());
            String token = jwtUtil.createToken(claims);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", registeredUser);
            return Result.success(data);
        } else {
            return Result.fail("注册失败，账号可能已存在");
        }
    }

    /**
     * 用户登录接口
     * @param user 用户信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody Users user) {
        if (user.getAccount() == null || user.getPassword() == null) {
            return Result.fail("账号和密码不能为空");
        }
        
        // 调用service进行登录验证
        Users loginUser = usersService.login(user.getAccount(), user.getPassword());
        if (loginUser != null) {
            // 生成JWT token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", loginUser.getUserId());
            claims.put("account", loginUser.getAccount());
            String token = jwtUtil.createToken(claims);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", loginUser);
            
            return Result.success(data);
        } else {
            return Result.fail("账号或密码错误");
        }
    }

    /**
     * 用户登出接口
     * @param token 用户的JWT token
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("Authorization") String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.fail("未提供有效的token");
        }
        String actualToken = token.substring(7);

        // 解析token获取过期时间
        Date expiration = jwtUtil.parseToken(actualToken).getExpiration();
        long expireMillis = expiration.getTime() - System.currentTimeMillis();
        if (expireMillis > 0) {
            // 存入Redis并设置过期时间
            redisTemplate.opsForValue().set("blacklist:" + actualToken, "1", expireMillis, java.util.concurrent.TimeUnit.MILLISECONDS);
        }

        return Result.success("退出登录成功");
    }

    /**
     * 获取当前用户信息
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo() {
        Integer userId = UserContextHolder.getUserId();
        if (userId == null) {
            return Result.fail("用户未登录或未提供有效的用户ID");
        }
        
        // 获取用户信息
        UserProfileVO user = usersService.getUserInfo(userId);
        if (user == null) {
            return Result.fail("获取用户信息失败，token可能无效或已过期");
        }
        
        return Result.success(user);
    }

    /**
     * 根据id返回用户信息
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public Result<?> getUserInfoById(@PathVariable Integer userId) {
        UserProfileVO user = usersService.getUserInfo(userId);
        if (user == null) {
            return Result.fail("获取用户信息失败，用户不存在");
        }
        return Result.success(user);
    }

    /**
     * 修改当前用户信息
     */
    @PutMapping("/update")
    public Result<?> updateUserInfo(@ModelAttribute UserDTO userDTO) {
        Integer userId = UserContextHolder.getUserId();
        if (userId == null) {
            return Result.fail("未登录或未提供有效账号");
        }
        Users user = usersService.getById(userId);
        user.setUsername(userDTO.getUsername());
        user.setBio(userDTO.getBio());
        user.setGender(userDTO.getGender());
        user.setBirthday(userDTO.getBirthday());
        user.setEmail(userDTO.getEmail());
        user.setPhone(userDTO.getPhone());
        if (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) {
            // 删除原图片
            if (user.getAvatar()!=null) {
                try {
                    // 从完整URL中提取文件路径
                    String objectName = user.getAvatar().substring(user.getAvatar().indexOf("/", 8));
                    ossUtil.deleteFile(objectName);
                } catch (Exception e) {
                    // 记录删除失败，但不影响整体流程

                }
            }
            // 上传新图片
            String avatarUrl = ossUtil.uploadFile(userDTO.getAvatar(), "avatars");
            user.setAvatar(avatarUrl);
        }
        // 更新用户信息
        Users updatedUser = usersService.updateUserInfo(userId, user);
        if (updatedUser == null) {
            return Result.fail("更新失败，请检查邮箱或手机号是否已被使用");
        }
        
        return Result.success(updatedUser);
    }

    /**
     * 修改密码
     * @param token 用户token
     * @return 修改结果
     */
    @PutMapping("/updatePassword")
    public Result<?> updatePassword(@RequestHeader("Authorization") String token, @RequestBody Map<String, String> request) {
        if (token == null || !token.startsWith("Bearer ")) {
            return Result.fail("未提供有效的token");
        }

        String actualToken = token.substring(7);
        String oldPassword = request.get("oldPassword");
        String newPassword = request.get("newPassword");
        
        // 更新密码
        boolean updated = usersService.updatePassword(actualToken, oldPassword, newPassword);
        if (!updated) {
            return Result.fail("旧密码错误");
        }
        
        return Result.success("密码更新成功");
    }

}
